package heartbeat

import (
	"fmt"
	"git.gz.internal.jumaiyx.cn/pkg/tnet/buffer"
	"git.gz.internal.jumaiyx.cn/pkg/tnet/route"
	"github.com/panjf2000/gnet/v2"
	"time"
)

type Heartbeat interface {
	Start()
	Stop()
}
type heartbeat struct {
	interval         time.Duration // 心跳间隔时间
	msgID            uint32        // 心跳的接受msgId
	router           route.IRouter // 心跳的路由
	conn             gnet.Conn     // 心跳绑定的连接
	quit             chan bool     // 退出心跳检测
	lastActivityTime int64         // 最后的检测时间
}

func NewHeartbeat(conn gnet.Conn, msgId uint32, router route.IRouter, interval time.Duration) Heartbeat {
	return &heartbeat{
		interval: interval,
		conn:     conn,
		msgID:    msgId,
		router:   router,
		quit:     make(chan bool, 1),
	}
}

func (hb *heartbeat) Start() {
	go func() {
		ticker := time.NewTicker(hb.interval)
		for {
			select {
			case <-ticker.C:
				hb.check()
			case <-hb.quit:
				ticker.Stop()
				return
			}
		}
	}()
}

func (hb *heartbeat) Stop() {
	hb.quit <- true
}

func (hb *heartbeat) check() {
	// 发送客户端通知
	bytes, _ := buffer.New(hb.msgID, []byte{})
	n, err := hb.conn.Write(bytes)
	if err != nil || n < 0 {
		// 断开连接
		fmt.Println(hb.conn.Fd(), ":检测不到心跳停止")
		_ = hb.conn.Close()
		hb.quit <- true
		return
	}
	hb.lastActivityTime = time.Now().Unix()
}
